package LC;

/**
 * https://leetcode.com/problems/merge-two-sorted-lists/description/
 * Merge two sorted linked lists and return it as a new list.
 * The new list should be made by splicing together
 * the nodes of the first two lists.
 */
public class LC_021_MergeTwoSortedLists_LinkedList {

    public static void main(String[] args) {
        ListNode head1 = new ListNode(0);
        head1.next = new ListNode(1);
        head1.next.next = new ListNode(2);
        head1.next.next.next = new ListNode(3);

        ListNode head2 = new ListNode(1);
        head2.next = new ListNode(2);
        head2.next.next = new ListNode(3);
        head2.next.next.next = new ListNode(4);

        //单独测试
        ListNode h2 = Solution_2.mergeTwoLists(head1, head2);
        printList(h2);

//        System.out.println();
//
//        ListNode h1 = Solution_1.mergeTwoListNode(head1, head2);
//        printList(h1);
    }

    static class ListNode {
        int val;

        ListNode next;

        public ListNode(int x) {
            this.val = x;
        }
    }

    private static void printList(ListNode head) {
        ListNode cur = head;
        while (cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
    }

    static class Solution_1 {
        private static ListNode mergeTwoListNode(ListNode l1, ListNode l2) {
            if (l1 == null)
                return l2;
            if (l2 == null)
                return l1;
            if (l1.val > l2.val) {
                l2.next = mergeTwoListNode(l1, l2.next);
                return l2;
            } else {
                l1.next = mergeTwoListNode(l1.next, l2);
                return l1;
            }

        }
    }

    static class Solution_2 {
        private static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if (l1 == null)
                return l2;
            if (l2 == null)
                return l1;
            ListNode cur;
            if (l1.val < l2.val) {
                cur = l1;
                l1 = l1.next;
            } else {
                cur = l2;
                l2 = l2.next;
            }
            ListNode fakeHead = new ListNode(-1);
            fakeHead.next = cur;
            while (l1 != null && l2 != null) {
                if (l1.val < l2.val) {
                    cur.next = l1;
                    cur = cur.next;
                    l1 = l1.next;
                } else {
                    cur.next = l2;
                    cur = cur.next;
                    l2 = l2.next;
                }
            }
            if (l1 != null)
                cur.next = l1;
            if (l2 != null)
                cur.next = l2;

            return fakeHead.next;
        }
    }

}
